import Storage from '@/utils/storage';
import { useCallback, useEffect, useState } from 'react';

const [CODE_STORE_KEY, CODE_EXECUTIONS_KEY] = [
  'go-execer.editor.code',
  'go-execer.editor.executions',
];
const [codeStore, execStore] = [
  new Storage(CODE_STORE_KEY),
  new Storage(CODE_EXECUTIONS_KEY),
];

const useEditor = () => {
  const [inited, setInited] = useState(false);
  const [codeData, setCodeData] = useState(null);
  const [executions, setExecutions] = useState([]);

  useEffect(() => {
    setCodeData(codeStore.get() || null);
    setExecutions(execStore.get() || []);
    setInited(true);
  }, []);
  useEffect(() => {
    if (inited) {
      codeStore.set(codeData);
    }
  }, [codeData]);
  useEffect(() => {
    if (inited) {
      execStore.set(executions);
    }
  }, [executions]);

  const saveCode = useCallback((data) => {
    setCodeData(data);
  }, []);
  const saveExecution = useCallback((data) => {
    setExecutions(v => {
      if (v.findIndex(item => item.id === data?.id) >= 0) {
        return v;
      }
      return [data, ...v];
    });
  }, []);

  return {
    codeData,
    executions,
    saveCode,
    saveExecution,
  };
};

export default useEditor;
